// pages/details/details.js
const app = getApp()
var wh = require("../../utils/wh.js");
var WxParse = require('../../wxParse/wxParse.js');
Page({

  /**
   * 页面的初始数据
   */ 
  data: {
    size: [{ a: '213' }, { a: '2s13' }, { a: '21s3' }, { a: '2s13' }, { a: '2ss13' }, { a: '213' }],
    morelists:[],
    coupon:[],
    index: '1',
    detailInfo:'',
    allImg: '',
    modal:false,
    istrue: true,
    goods_id:'',
    ShopDetail:'',
    CollectHave:'',
    likeNum: '',
    ShareCount: '',
    couponlength:'',
    page: 1,
    page_size: 5,
    no_data: 0,
    onearth: false, // 是否已经到达底部
    comments:[],
    user_just:'',
    maskHidden: false, // 海报
    have: true,
    url:'',
    BuyItNow:false,
    num:1
  }, 
  nav() {
    this.setData({
      no_data: 0,
      page: 1,
      page_size: 5,
      onearth: false,
      have: true,
      comments: [],
    });
    this.good_comments()
    let istrue = this.data.istrue
    this.setData({
      istrue: !istrue
    })
  },
  bindchange: function (e) {
    this.setData({
      index: e.detail.current + 1,
    })
  },
  colse(){
    this.setData({
      modal: false
    })
  },
  BuyItNow() {
    this.setData({
      BuyItNow:true
    })
  },
  close() {
    this.setData({
      BuyItNow: false
    })
  },
  sizechoose(e){
    console.log(e)
    let that = this,
    // 选中
    list = this.data.size,
      inx = e.currentTarget.dataset.inx;
    for (let i in list) {
      list[i].is_default = 0;
    }
    let is_default = list[inx].is_default;
    list[inx].is_default = 1;
    that.setData({
      size: list
    });
  },
  // 数量增减按钮
  subtract() {
    let num = parseInt(this.data.num);
    if (num <= 1) {
      return
    } else {
      num = num - 1;
      this.setData({
        num: num
      })
    }

  },
  add() {
    let num = parseInt(this.data.num);
    num = num + 1;
    this.setData({
      num: num
    })
  },

  // 获取商品评价列表
  good_comments(){
    let that = this;
    let page_size = this.data.page_size, 
      no_data = this.data.no_data,
      page = this.data.page;
    if (no_data == 0) {
      wh.Post('/api/mall.comment/good_comments', {
        page: page,
        page_num: page_size,
        goods_id: that.data.detailInfo.goods_id
      }, function (res) {
        console.log('商品评价列表',res)
        let shop = that.data.comments.concat(res.list),
          count = res.list.length;
        if (page_size > count) {
          that.data.no_data = 1;
          if (shop.length > 3) {
            that.setData({
              onearth: true
            })
          }
        }
        that.setData({
          comments: shop
        })
        if (that.data.comments.length == 0) {
          that.setData({
            have: false,
          });
        } else {
          that.setData({
            have: true,
          });
        }
      })
    }
  },
  //获取优惠券
  getCoupon: function () {
    let that = this,
      modal = this.data.modal;
      wh.Post("/api/mall.coupon/lists", {
        page: 1,
        page_num: 10,
        goods_id: that.data.detailInfo.goods_id,
        shop_id: that.data.detailInfo.shop_id,
      }, function (res) {
        console.log('获取优惠券', res)
        if (res.length == 0) {
            modal=false
        }else{
            modal=true
        }
        that.setData({
          coupon: res,
          modal: modal
        });
      })
  },
  //获取优惠券条数
  getCouponlength(shop_id, goods_id){
    let that = this;
    wh.Post("/api/mall.coupon/lists", {
      page: 1,
      page_num: 10,
      shop_id: shop_id,
      goods_id: goods_id,
    },function(res){
      that.setData({
        couponlength: res.length,
      });
    })
  },
  //领取优惠券
  linquCoupon: function (e) {
    let that = this;
    let coupon_id = e.currentTarget.dataset.id;
    let idx = e.currentTarget.dataset.idx;
    let coupon = that.data.coupon;
    wh.Post('/api/mall.coupon/receive', { coupon_id: coupon_id }, function (res) {
      coupon[idx].is_receive = 1
      that.setData({
        coupon: coupon
      })
      wx.showToast({ title: '领取成功', icon: 'none' });
    })
  },
  // 查看是否收藏
  CollectHave(goods_id) {
    var that = this;
    wh.Post('/api/mall.collect/have', {
      target_id: goods_id,
      type: 1
    }, function (res) {
      console.log('是否收藏', res)
      that.setData({
        CollectHave: res
      })
    });
  },
  // 收藏提交
  CollectSubmit() {
    var that = this;
    wh.Post('/api/mall.collect/submit', {
      target_id: that.data.goods_id,
      type: 1
    }, function (res) {
      that.ColletcTotal(that.data.goods_id)
      let CollectHave = !that.data.CollectHave;
      that.setData({
        CollectHave: CollectHave
      })
    })
  },
  // 获取收藏喜欢统计
  ColletcTotal(goods_id){
    var that = this;
    wh.Post('/api/mall.collect/total', {
      target_id: goods_id,
      type: 1
    }, function (res) {
      that.setData({
        likeNum: res
      })
    })
  },
  // 获取商家店铺详情
  getShopDetail(shop_id) {
    var that = this;
    wh.Post('/api/mall.shop/detail', {
      shop_id: shop_id
    }, function (res) {
      console.log('店铺详情', res)
      that.setData({
        ShopDetail: res,
      })
    });
  },
  // 获取店铺分享统计信息
  getShareCount(shop_id) {
    var that = this;
    wh.Post('/api/mall.share/get_count', {
      shop_id: shop_id
    }, function (res) {
      console.log('获取店铺分享统计信息', res)
      that.setData({
        ShareCount: res,
      })
    });
  },
  // 更多经典
  morelists(shop_id) {
    let that = this;
    wh.Post('/api/mall.goods/lists', {
      shop_id: shop_id,
      is_recom: 1,
      is_hot: 1
    }, function (res) {
      that.setData({
        morelists: res
      })
      console.log('更多经典', res)
    })
  },
  // 记录用户访问足迹
  FootMarkRecord(shop_id) {
    wh.Post('/api/mall.footmark/record', {
      shop_id: shop_id,
      target_id: shop_id,
      type: 1
    }, function (res) {

    })
  },
  // 获取商品详情
  detail(goods_id){ 
    let that = this;
    wh.Post('/api/mall.goods/detail', {
      goods_id:goods_id
    }, function (res) {
      // that.FootMarkRecord(res.shop_id)
      that.morelists(res.shop_id)
      that.getShareCount(res.shop_id)
      that.getShopDetail(res.shop_id)
      that.getCouponlength(res.shop_id, res.goods_id) 
      if (res.goods_info) { 
      WxParse.wxParse('goods_detail', 'html', res.goods_info, that)
      };
      console.log('商品详情',res)
      that.setData({
        detailInfo: res,
        allImg: res.cover_album.length
      })
    })
  },
  // 记录店铺分享
  RecordShare() {
    let that = this;
    wh.Post("/api/mall.share/record_share", { shop_id: that.data.detailInfo.shop_id }, function (res) {
      that.getShareCount(that.data.detailInfo.shop_id)
    })
  },
  // 某某某刚刚购买了商品
  user_just(goods_id) {
    let that = this;
    wh.Post('/api/mall.goods/just', {
      goods_id: goods_id
    }, function (res) {
      console.log('某某某刚刚购买了商品', res)
      that.setData({
        user_just: res
      })
    })
  },
  // 获取url
  url(){
    let that=this;
    wx.getExtConfig({
      success: function (res) {
        console.log(2, res)
        let url = res.extConfig.apiurl;
        that.setData({
          url:url
        })
      }
    })
  },
  /** 
   * 生成海报
   */
  createPoster: function () {
    let param = this.data.detailInfo,
      url = this.data.url,
      that = this,
      postUrl = '/api/mall.ajax/page_qrcode',
      tag = false,
      s_url = 'pages/details/details?goods_id=' + this.data.detailInfo.goods_id
      ;
    setTimeout(() => {
      wx.showToast({
        title: '海报生成中...',
        icon: "loading",
      });
      setTimeout(() => {
        wx.hideToast();
      }, 10000)
    }, 0);
    // 获取小程序码
    wh.Post(postUrl, { s_url: s_url }, function (imgUrl) {
      console.log(imgUrl)
      // 将图片保存到本地
      wx.getImageInfo({
        src: param.cover,   //请求的网络图片路径
        success: function (res1) {
          param.path1 = res1.path;
          wx.getImageInfo({
            src: imgUrl,    //请求的网络图片路径
            success: function (res2) {
              param.path2 = res2.path;
              // 开始绘制
              app.startToDraw(param, url, tag, imgUrl);
              that.setData({
                maskHidden: true
              });
              // 将生成好的图片保存到本地，需要延迟一会，绘制期间耗时
              setTimeout(function () {
                // wx.hideLoading()
                wx.canvasToTempFilePath({
                  canvasId: 'mycanvas',
                  success: function (res) {
                    var tempFilePath = res.tempFilePath;
                    that.setData({
                      imagePath: tempFilePath,
                      canvasHidden: true
                    });
                  },
                  fail: function (res) {
                    console.log(res);
                  }
                });
              }, 200);
            }
          });
        }
      });
    });
  },
  /**
   * 点击保存到相册
   */
  poster_save: function () {
    var that = this
    wx.saveImageToPhotosAlbum({
      filePath: that.data.imagePath,
      success(res) {
        that.setData({
          maskHidden: false
        });
        wx.showToast({
          title: '图片已保存到相册',
        });
      }
    })
  },
  /**
   * 关闭海报
   */
  close_share: function () {
    this.setData({
      maskHidden: false
    })
  },
  toSubmit(){
    let that=this;
    wh.Post("/api/mall.cart/add", { 
      goods_id: that.data.detailInfo.goods_id,
      buy_num: that.data.num
     }, function (res) {
      wx.navigateTo({
        url: '../submit/submit?cart_id=' + res +'&istype=' + 4,
      })
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('options', options)
    this.url()
    this.detail(options.goods_id)
    this.CollectHave(options.goods_id)
    this.user_just(options.goods_id)
    this.ColletcTotal(options.goods_id)
    this.setData({
      goods_id: options.goods_id,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      no_data: 0,
      page: 1,
      page_size: 5,
      onearth: false,
      comments: [],
    });
    this.good_comments()
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let no_data = this.data.no_data,
      page = this.data.page,
      page_size = this.data.page_size;
    if (no_data == 0) {
      this.data.page = page + 1;
      this.good_comments()
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let that = this;
    return {
      title: that.data.detailInfo.title,
      path: '/pages/cutDetails/cutDetails?goods_id=' + that.data.goods_id,
      imageUrl: that.data.detailInfo.cover,
      success: function (res) {
        that.RecordShare()
        console.log('转发成功')
      }
    }
  }
})